import { Module } from 'vuex'

import { iLoginState } from './type'
import { IRootState } from '../type'
import { loginReq, userInfoReq, userRoles } from '@/service/login/login'
import LocalCache from '@/utils/cache'
import router from '@/router'

const login: Module<iLoginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      token: '',
      userInfo: {},
      userMenus: []
    }
  },
  mutations: {
    CHANGETOKEN(state, token: string) {
      state.token = token
    },
    SAVEUSERINFO(state, userInfo: any) {
      state.userInfo = userInfo
    },
    SAVEMENUS(state, menus) {
      menus[0].icon = 'monitor'
      menus[1].icon = 'setting'
      menus[2].icon = 'goods'
      menus[3].icon = 'ChatDotRound'
      state.userMenus = menus
      LocalCache.setCache('userMenus', menus)
    },
    SAVEVUEXTOKEN(state, token) {
      state.token = token
    },
    SAVEVUEXUSERINFO(state, userInfo) {
      state.userInfo = userInfo
    },
    SAVEVUEXMENUS(state, userMenus) {
      state.userMenus = userMenus
    }
  },
  actions: {
    async loginNow({ commit }, nameAndpass) {
      try {
        const idAndToken = await loginReq(nameAndpass)
        const { id, token } = idAndToken.data
        LocalCache.setCache('token', token)
        commit('CHANGETOKEN', token)
        const userInfo = await userInfoReq(id)
        commit('SAVEUSERINFO', userInfo.data)
        LocalCache.setCache('userInfo', userInfo.data)
        const roles = await userRoles(userInfo.data.role.id)
        commit('SAVEMENUS', roles.data)
        // LocalCache.setCache('userMenus', roles.data)
        router.push('/main')
      } catch (error) {
        return '异常'
      }
    },
    storeLocalData({ commit }) {
      const token = LocalCache.getCache('token')
      if (token) {
        commit('SAVEVUEXTOKEN', token)
      }
      const userInfo = LocalCache.getCache('userInfo')
      if (userInfo) {
        commit('SAVEVUEXUSERINFO', userInfo)
      }
      const userMenus = LocalCache.getCache('userMenus')
      if (userMenus) {
        commit('SAVEVUEXMENUS', userMenus)
      }
    }
  },
  getters: {}
}

export default login
